import requests
from .PaiToken import PaiToken
import os
import time

class TaskSetInterface:
    def to_json(self):
        pass

    def name(self):
        pass

    def state(self):
        pass

    def duration(self):
        pass

    def createdTime(self):
        pass

    def completedTime(self):
        pass

    def user(self):
        pass


class TaskSet(TaskSetInterface):
    def __init__(self, json_object):
        self.json_object = json_object

    def name(self):
        return self.json_object['name']

    def state(self):
        return self.json_object['state']

    def user(self):
        return self.json_object['userId']

    def createdTime(self):
        return  self.json_object['createdTime']

    def completedTime(self):
        return (self.json_object['completedTime']
                if self.json_object['completedTime'] > 0 else time.time()*1000)

    def duration(self):
        if self.json_object['completedTime'] > 0 :
            return self.json_object['completedTime'] - self.json_object['createdTime']

        return time.time()*1000 - self.json_object['createdTime']

class TaskClient:
    def __init__(self, rest_server_url, token_config):
        self.job_server_url = rest_server_url + '/api/v1/jobs'
        self.token_server_url = rest_server_url + '/api/v1/token'
        self.token_config = token_config
        self.no_token = os.getenv("NOTOKEN", "")

    @property
    def token(self):
        return PaiToken(self.token_config, self.token_server_url).getToken()

    def get_headers(self):
        if not self.no_token or self.no_token.lower() == "no":
            return {
                    'Authorization': u'Bearer ' + self.token,
                    # 'Content-type': u'application/json'
                }

        return {}


    def list_jobs(self):
        try:
            response = requests.get(
                self.job_server_url,
                headers = self.get_headers()
            )

            return response.json()
        except Exception as err:
            raise Exception("[get_jobs_list] err {}".format(err))

    # 根据关键字筛选任务列表
    def get_jobs_list_by_key(self, search_multi_key):
        import re
        def filter_jobs_by_key(jobs_list, filter_key):
            searched_jobs = []
            for job in jobs_list:
                # 当前实现方式直接将job信息导成字符串，然后在字符串中搜索
                job_str = str(job)
                if re.search(filter_key, job_str, re.IGNORECASE):
                    searched_jobs.append(job)
            return searched_jobs

        try:
            response = requests.get(
                self.job_server_url,
                headers=self.get_headers()
            )
            searched_jobs = response.json()
            # 遍历任务筛选符合条件的任务
            # 通过逗号支持多个关键字
            search_key_list = search_multi_key.split(',')
            for search_key in search_key_list:
                searched_jobs = filter_jobs_by_key(searched_jobs, search_key)

            return searched_jobs
        except Exception as err:
            raise Exception("[get_jobs_list_by_key] err {}".format(err))

    # 根据任务明停止任务
    def stop_job(self, job_name):
        stop_job_url = "{0}/{1}/executionType".format(self.job_server_url, job_name)
        try:
            requests.put(
                stop_job_url,
                data={'value': 'STOP'},
                headers=self.get_headers()
            )
        except Exception as err:
            raise Exception("stopping job:{0} error: {1}".format(job_name, err))

    def get_job_detail(self, job_name):
        try:
            response = requests.get(
                self.job_server_url + '/{}'.format(job_name),
                headers=self.get_headers()
            )

            job_detail = response.json()

            response_config = requests.get(
                self.job_server_url + '/{}/config'.format(job_name),
                headers=self.get_headers()
            )

            job_config = response_config.json()
            job_detail['jobConfig'] = job_config

            return job_detail

        except Exception as err:
            raise Exception("[get_job_detail] err {}".format(err))


    def get_batch_jobs(self, namelist):
        nameliststr = ",".join(namelist)
        batch_job_url = "{}/batchjob/{}".format(self.job_server_url, nameliststr)

        try:
            print("batch_job_url {}".format(batch_job_url))
            response = requests.get(
                batch_job_url,
                headers = self.get_headers()
            )

            return [TaskSet(taskset_json)  for taskset_json in response.json()]
        except Exception as err:
            raise Exception("[get_batch_jobs] err {}".format(err))